﻿//
// Created by Administrator on 2025/3/25.
//

#include "App.h"
#include <iostream>
#include <filesystem>
#include <imgui.h>
#include "str.h"
#include "bass.h"
#include "util.h"
namespace fs = std::filesystem;


App::App() {
    std::wcout.imbue(std::locale("chs"));
    const std::wstring path = getUserMusicPath();
    findMusicFile(path);
    BASS_Init(-1, 44100, BASS_DEVICE_CPSPEAKERS, nullptr, 0);
}

App::~App() {
}

void App::init() {
}

void App::appRender() {
    ImGui::ShowDemoWindow();

    if (ImGui::Begin(u8"窗口")) {
        static int current_item = 0;
        static HSTREAM hstream;

        if (ImGui::BeginListBox("My List", ImVec2(-FLT_MIN, 15 * ImGui::GetTextLineHeightWithSpacing()))) {
            for (int i = 0; i < items.size(); i++) {
                const bool is_selected = (current_item == i);
                if (ImGui::Selectable(items[i].filename.c_str(), is_selected)) {
                    current_item = i;
                    if (0 != hstream) {
                        BASS_ChannelStop(hstream);
                        BASS_ChannelFree(hstream);
                    }
                    hstream = BASS_StreamCreateFile(false, items[i].fullFileName.c_str(), 0, 0, BASS_SAMPLE_FLOAT);
                    BASS_ChannelPlay(hstream, false);
                }


                // 设置默认选中项
                if (is_selected) {
                    ImGui::SetItemDefaultFocus();
                }
            }
            ImGui::EndListBox();
        }
        ImGui::End();
    }
}
int App::findMusicFile(const std::wstring& path) {
    for (const auto &it: fs::directory_iterator(path)) {
        const std::wstring exts[] = {L".mp3",L".flac",L".m4a"};
        if (it.is_regular_file()) {
            for (const auto & ext : exts) {
                if (ext==it.path().extension()) {
                    MuiscFileInfo muisc_file_info;
                    const auto fullFileName = it.path().wstring();
                    muisc_file_info.fullFileName = fullFileName;
                    auto filename = it.path().filename().wstring();
                    muisc_file_info.filename = Utf16ToUtf8(filename);

                    items.push_back(muisc_file_info);
                    break;
                }
            }
        }else if (it.is_directory()) {
            findMusicFile(it.path());
        }
    }
    return  items.size();
}

